<!doctype html>
<html>
<head>
  <style>
    
    #my-canvas { border: 1px solid gray; }
    
  </style>
</head>
<body>
  <script src="/js/axios.min.js"></script>
  <canvas id="my-canvas" width="512" height="512"></canvas>
  <script>

    const downloadData = async () => {
       const resp = await axios.get('/image',{responseType: 'arraybuffer'});
       return resp.data;
    }
    
    const sleep = (interval) => {
      return new Promise(resolve => {
        setTimeout(resolve, interval);
     })
    }

    var canvas = document.querySelector('#my-canvas');
    var context = canvas.getContext('2d');
      // to increase performance createImageData method 
      // should be executed once e.g. before drawing
      var image = context.createImageData(canvas.width, canvas.height);
      var data = image.data;
      var dataView = new Uint32Array(data.buffer);
      const height = canvas.height;
      const width = canvas.width;
      const byteLength = height*width;

      function drawPixel(i, value) {
            dataView[i] =
            (255   << 24) |	// alpha
            (value << 16) |	// blue
            (value <<  8) |	// green
             value;		// red
       } 
       
       function swapBuffer() {
          context.putImageData(image, 0, 0);
        }



    const showData = async () => {
      var buf = await downloadData();

       if(buf.byteLength < byteLength)
       {
           console.log("error:downloaded buffer's size is smaller than canvas's size");
           return;
       }
      var bufView = new Uint8Array(buf);     

      var t1 = new Date();
       
        for(var y = 0; y < height; ++y) {
          for(var x = 0; x < width; ++x) {
            var index = y*height + x;
            var gray = bufView[index];
            //var color = { r : gray, g: gray, b:gray, a:255 };
            drawPixel(index, gray);
        }
      }

        swapBuffer();

        var t2 = new Date();
        var dt = t2 - t1;
        console.log('elapsed time = ' + dt + ' ms');
    }

    const animate = () => {
      showData().then( () =>
        window.requestAnimationFrame(animate)
       ).catch(err => console.log(err));
    }
    

    window.requestAnimationFrame(animate)

  </script>
</body>
</html>